<?php
uses('L10n');
class AppController extends Controller {
    public $components     = array('Cookie', 'FirePHP', 'RequestHandler');
    public $helpers        = array('Html', 'Javascript');
    public $stylesheet     = array();
    public $javascripts    = array('ext-core'); // http://ajax.googleapis.com/ajax/libs/ext-core/3.0.0/ext-core-debug.js
    public $firePHP        = false;
    public $allowedActions = 'all'; // Provides access for actions which most often do not require any access control.
    public $loginRedirect  = '/members/home'; // where to go after a successful login?
	public $ext            = '.html';
    public $serverTimezone = 'Asia/Kuala_Lumpur'; // 'GMT'
    public $clientTimezone = 'Asia/Kuala_Lumpur';
    public $sendmailFrom   = 'noreply@localhost';
    public $merchantKey    = 'orange';
    public $merchantCode   = 'M00160';
    public $scaffold;

    public function beforeFilter () {
        //$this->loadSettings();
        Configure::write('site.sitename', 'CARE LATEX');

        date_default_timezone_set($this->serverTimezone);
        define('SERVER_TIMEZONE', $this->serverTimezone);
        define('CLIENT_TIMEZONE', $this->clientTimezone);
        define('CLIENT_TIMEZONE_OFFSET',  timezone_offset_get(timezone_open($this->clientTimezone), date_create()));

        if ($this->RequestHandler->isAjax()) { // request contains the X-Requested-Header equal to XMLHttpRequest
            if (!class_exists('FirePHP')) { // change the debug level to 0 for all Ajax requests without FirePHP Server Lib included
                Configure::write('debug', 0);
            } else {
                Configure::write('debug', 2);
                $this->firePHP = true;
                //$this->debugMsg('It is an AJAX request and FirePHP Server Lib included. @ ['.__FILE__.']', 'info');
            }
            $m = $this->RequestHandler->getReferrer();
        }

        if ($lang = $this->Cookie->read('User.language')) { // user language
            $this->L10n = new L10n();
            $this->L10n->get('zh');
        }

        $role = $this->Session->read('Member.role'); //Auth.User.role
        if ($role == 'A') {
            $this->set('admin', true);
        } else {
            $this->set('admin', false);
        }
        $this->set('logged', $role);

        if (substr($this->params['action'], 0, 6) == 'admin_') { // is in admin panel?
            $this->layout     = 'admin';
            $this->stylesheet = am($this->stylesheet, 'admin');

            if (!$role && $this->params['action'] != 'admin_login') { // not logged yet
                if ($this->RequestHandler->isAjax()) {
                    $this->params['action'] = 'admin_ajax_login';
                } else {
                    $this->redirect('/admin/members/login');
                }
            } else if ($role != 'admin') { // not administrator
                //__('Invalid access!',true);
            }
        } else {
            $this->stylesheet = am($this->stylesheet, 'common');
        }
    } // beforeFilter

    public function beforeRender () {
        $jscripts = is_array($this->javascripts) ? $this->javascripts : array($this->javascripts);
        $this->set('stylesheet', $this->stylesheet);
        $this->set('javascripts', $jscripts);
        $this->set('sitename', Configure::read('site.sitename'));
    } // beforeRender

    public function checkAuth () {
        if (isset($this->Auth)) {
            $this->Auth->autoRedirect = false;
            $this->Auth->mapActions(array('display'=>'read'));

            // tell Auth which actions do not need any access control
            if (isset($this->allowedActions)) { // shared between all application's controllers
               $this->Auth->allow($this->allowedActions);
            }
            if (isset($this->publicActions)) { // use in controller extended AppController
               $this->Auth->allow($this->publicActions);
            }

            $this->Auth->fields        = array('username'=>'email', 'password'=>'password');
            $this->Auth->userScope     = array('Member.status'=>'A');
            $this->Auth->loginAction   = '/members/login';
            $this->Auth->loginRedirect = $this->loginRedirect;
            //$this->Auth->authorize = 'controller';
            $this->Auth->loginError    = '<h4>'.__('Sorry, login failed. Either your username or password are incorrect.', true).'</h4>';
            $this->Auth->authError     = '<h4>'.__('The page you tried to access is restricted. You have been redirected to the page below.', true).'</h4>';
        }
    } // checkAuth

    public function loadSettings () {
        App::import('Model', 'Setting');
        $o_setting = new Setting();

        $params = array(
            'fields' => 'Setting.category, Setting.short_name, Setting.value',
            'order'  => 'Setting.category ASC, Setting.position ASC'
        );
        $settings = $o_setting->find('all', $params);

        foreach ($settings as $data) {
            $key   = $data['Setting']['category'].'.'.$data['Setting']['short_name'];
            $value = $data['Setting']['value'];
            Configure::write($key, $value);
        }
    } // loadSettings

    public function clientToServerTime ($datetime, $format='Y-m-d H:i:s') {
        date_default_timezone_set($this->clientTimezone); // switch to client timezone first

        $datetimeObject = date_create($datetime); // create datetime object
        $serverTimezone = timezone_open($this->serverTimezone); // create server timezone object

        date_timezone_set($datetimeObject, $serverTimezone); // switch datetime object follow server timezone

        return date_format($datetimeObject, $format);
    } // clientToServerTime

    public function serverToClientTime ($datetime, $format='Y-m-d H:i:s') {
        date_default_timezone_set($this->serverTimezone); // switch to server timezone first

        $datetimeObject = date_create($datetime); // create datetime object
        $clientTimezone = timezone_open($this->clientTimezone); // create client timezone object

        date_timezone_set($datetimeObject, $clientTimezone); // switch datetime object follow client timezone

        return date_format($datetimeObject, $format);
    } // serverToClientTime

    public function response ($json) {
        $this->set('json', $json);
        $this->render(false, 'json');
    } // response

    public function debugMsg ($message, $type) {
        if (!class_exists('FirePHP')) {
            return false;
        }

        switch ($type) {
           case 'error':
             $this->FirePHP->error($message);
             break;

           case 'warn':
             $this->FirePHP->warn($message);
             break;

           case 'info':
           default:
             $this->FirePHP->info($message);
             break;
        }
    } // debugMsg

    public function _checkLogged ($role='') {
        $logged = $this->Session->read('Member.id');

        if ($logged) {
            if ($role && $role != $this->Session->read('Member.role')) {

            } else {
                return true;
            }
        }
        if ($this->RequestHandler->isAjax()) {
            $json = array(
                'status' => -2
            );
            $this->response($json);
            return false;
        }

        $this->redirect('/members/login');
    } // _checkLogged
} // AppController
